
#include "stdafx.h"
#include "NIPAddr.h"



NIPAddr::NIPAddr() : m_IPAddr(0)
{

}

NIPAddr::NIPAddr( const DWORD in_IPAddr )
{
	Set( in_IPAddr );
}

NIPAddr::NIPAddr( const string in_IPaddr )
{
	Set( in_IPaddr );
}

NIPAddr::~NIPAddr()
{


}

void NIPAddr::Set( const string in_IPAddr )
{
	m_IPAddr = inet_addr( in_IPAddr.c_str() );
}

bool NIPAddr::IsPrivateIP( DWORD in_IPaddr )
{
    WORD wLo  = LOWORD( in_IPaddr );
	WORD wHi  = HIWORD( in_IPaddr );
	BYTE a = LOBYTE(wLo);
	BYTE b = HIBYTE(wLo);
	BYTE c = LOBYTE(wHi);
	BYTE d = HIBYTE(wHi);

	DWORD dwNewIP = MAKELONG(MAKEWORD(d, c), MAKEWORD(b, a));

	DWORD dwIP_1 = NIPAddr("10.0.0.0");
	DWORD dwIP_2 = NIPAddr("10.255.255.255");
	if(dwNewIP >= dwIP_1 && dwNewIP <= dwIP_2) return true;

	dwIP_1 = NIPAddr("172.16.0.0");
	dwIP_2 = NIPAddr("172.31.255.255");
	if(dwNewIP >= dwIP_1 && dwNewIP <= dwIP_2) return true;

	dwIP_1 = NIPAddr("192.168.0.0");
	dwIP_2 = NIPAddr("192.168.255.255");
	if(dwNewIP >= dwIP_1 && dwNewIP <= dwIP_2) return true;

	return false;
}

DWORD NIPAddr::GetHostIP( bool in_bPUBLIC )
{
	char HostName[255] = "";
	if( SOCKET_ERROR == ::gethostname( HostName, sizeof(HostName) ) ) return 0;
	PHOSTENT pHostInfo = ::gethostbyname( HostName );
	if( NULL == pHostInfo ) return 0;

	for( int idx = 0; pHostInfo->h_addr_list[ idx ]; ++idx )
	{
		DWORD HostIP = reinterpret_cast< in_addr far*>( pHostInfo->h_addr_list[ idx ] )->s_addr;
		if( ( false == in_bPUBLIC ) && IsPrivateIP( HostIP ) ) return HostIP;
		if( ( true == in_bPUBLIC ) && ( false == IsPrivateIP( HostIP ) ) ) return HostIP;
	}
	return 0;
}


const char* NIPAddapter( NIPAddr in_IPAddr )
{	
	struct threadBuffer{ char m_buffer[16]; };
	static map< int, threadBuffer > tbl;

	threadBuffer& th = tbl[ reinterpret_cast<int>( ::GetCurrentThread() ) ];
	in_addr	Addr = { 0, };
	Addr.S_un.S_addr = in_IPAddr;
	::_snprintf_s( th.m_buffer, sizeof( th.m_buffer ), _TRUNCATE, "%s", ::inet_ntoa( Addr ) );
	return th.m_buffer;
}



